//
//  ComonDataService.m
//  HZHome
//
//  Created by SunShine on 13-9-21.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "CommonDataService.h"
#import "NSObject+propertyList.h"
#import "UserInfoService.h"
@implementation CommonDataService

- (id)init
{
    self = [super init];
    if (self) {
        __block CommonDataService* weakSelf = self;
        SuccessBlock = ^(id json){
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadDataFinished)]) {
                [weakSelf.delegate loadDataFinished];
            }
        };
        FailBlock = ^(NSError *err) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadDataFaild:)]) {
                [weakSelf.delegate loadDataFaild:@"获取数据失败."];
            }
        };
    }
    return self;
}

-(void)loadDataWithKey:(NSString *)keyOrNil
{
    //super implements did nothing!
}

-(void)loadMoreDataWithKey:(NSString *)keyOrNil
{
    //super implements did nothing!
}

-(NSArray *)getSegmentsTitles
{
    //super implements retrun nothing!
    return nil;
}

-(NSArray *)getSegmentsTitles:(int)index
{
    return nil;
}

-(void)selectSegmentBarAtIndex:(NSInteger)selected
{
    //super implements did nothing!
}

-(void)configCell:(UITableViewCell*)cell atIndex:(NSIndexPath*)index
{
    //super implements did nothing!
}

-(CGFloat)heightForCellAtRow:(NSIndexPath *)index
{
    //super implements return default 44.0
    return 44.0f;
}
-(void)doHttpPost:(NSString *)posturl headers:(NSDictionary*)headersOrNil path:(NSString*)path parameters:(NSDictionary *)params
{
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userId"];
    }
    _currentEngine = [[MKNetworkEngine alloc] initWithHostName:posturl customHeaderFields:headersOrNil];
    MKNetworkOperation *op = [_currentEngine operationWithPath:path params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        
        NSDictionary *json = [operation responseJSON];
        //转换对象,添加到列表中
        if (![[json objectForKey:@"pageList"] isKindOfClass:[NSNull class]]) {
            [self initDataItem:_dataItemName withArray:[json objectForKey:@"pageList"]];
        } else {
            [self initDataItem:_dataItemName withArray:nil];

        }
        //判断是否有下一页
        int totalCount = ((NSNumber*)[json objectForKey:@"totalCount"]).intValue;
        bool hasNextPage = self.dataList.count < totalCount;
        if (self.delegate && [self.delegate respondsToSelector:@selector(setEnableToLoadMore:)]) {
            [self.delegate setEnableToLoadMore:hasNextPage];
        }
        //读取当前的页码
        _currentPageNo = ((NSNumber*)[json objectForKey:@"currentPageNo"]).intValue;
        //执行回调
        SuccessBlock(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        
        //执行回调
        FailBlock(err);
    }];
    [_currentEngine enqueueOperation:op];
}

-(void)doHttpPost:(NSString *)posturl  path:(NSString*)path parameters:(NSDictionary *)params
{
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userId"];
    }
    _currentEngine = [[MKNetworkEngine alloc] initWithHostName:posturl customHeaderFields:nil];
    MKNetworkOperation *op = [_currentEngine operationWithPath:path params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        
        NSDictionary *json = [operation responseJSON];
        //转换对象,添加到列表中
        
        [self initDataItem:_dataItemName withDict:json];
        //判断是否有下一页
        int totalCount = ((NSNumber*)[json objectForKey:@"totalCount"]).intValue;
        bool hasNextPage = self.dataList.count < totalCount;
        if (self.delegate && [self.delegate respondsToSelector:@selector(setEnableToLoadMore:)]) {
            [self.delegate setEnableToLoadMore:hasNextPage];
        }
        //读取当前的页码
        _currentPageNo = ((NSNumber*)[json objectForKey:@"currentPageNo"]).intValue;
        //执行回调
        SuccessBlock(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        
        //执行回调
        FailBlock(err);
    }];
    [_currentEngine enqueueOperation:op];
}

- (void)initDataItem:(NSString*)itemClassName withDict:(NSDictionary*)dict
{
    NSMutableArray *tempArray = [NSMutableArray array];
    if (self.dataList && self.dataList.count>0) {
        [tempArray addObjectsFromArray:self.dataList];
    }
    Class tempClass =  NSClassFromString(itemClassName);
    if (!tempClass) {
        return;
    }
    NSArray *properties = [tempClass getPropertyList];
    id item = [[tempClass alloc]init];
    for (NSString *propertyName in properties) {
        NSString *key = propertyName;
        if ([propertyName isEqualToString:@"Id"]) {
            key = @"id";//因为属性不能叫做id所以把I变成了大写
        }
        [item setValue:[dict objectForKey:key] forKey:propertyName];
    }
    [tempArray addObject:item];
    self.dataList = nil;
    self.dataList = tempArray;
    
}


-(void)doHttpGet:(NSString *)posturl headers:(NSDictionary *)headersOrNil path:(NSString *)path parameters:(NSDictionary *)params
{
    _currentEngine = [[MKNetworkEngine alloc] initWithHostName:posturl customHeaderFields:headersOrNil];
    MKNetworkOperation *op = [_currentEngine operationWithPath:path params:params httpMethod:@"GET"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        
        NSDictionary *json = [operation responseJSON];
        //转换对象,添加到列表中
        [self initDataItem:_dataItemName withArray:[json objectForKey:@"pageList"]];
        //判断是否有下一页
        int totalCount = ((NSNumber*)[json objectForKey:@"totalCount"]).intValue;
        bool hasNextPage = self.dataList.count < totalCount;
        if (self.delegate && [self.delegate respondsToSelector:@selector(setEnableToLoadMore:)]) {
            [self.delegate setEnableToLoadMore:hasNextPage];
        }
        //读取当前的页码
        _currentPageNo = ((NSNumber*)[json objectForKey:@"currentPageNo"]).intValue;
        //执行回调
        SuccessBlock(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        
        //执行回调
        FailBlock(err);
    }];
    [_currentEngine enqueueOperation:op];
}

-(void)initDataItem:(NSString*)itemClassName withArray:(NSArray*)array
{
    NSMutableArray *tempArray = [NSMutableArray array];
    if (self.dataList && self.dataList.count>0) {
        [tempArray addObjectsFromArray:self.dataList];
    }
    Class tempClass =  NSClassFromString(itemClassName);
    if (!tempClass) {
        return;
    }
    NSArray *properties = [tempClass getPropertyList];
    for (NSDictionary *dic in array) {
        id item = [[tempClass alloc]init];
        for (NSString *propertyName in properties) {
            NSString *key = propertyName;
            if ([propertyName isEqualToString:@"Id"]) {
                key = @"id";//因为属性不能叫做id所以把I变成了大写
            }
            [item setValue:[dic objectForKey:key] forKey:propertyName];
        }
        [tempArray addObject:item];
    }
    self.dataList = nil;
    self.dataList = tempArray;
}

-(void)cancelAllRequest
{
    [_currentEngine cancelAllOperations];
}

-(void)configInfoWithPhoneAndMapCell:(InfoWithPhoneAndMapCell *)cell withItem:(CommonMineQueryItem *)item atIndex:(NSInteger)index
{
    cell.mainInfoLabel.text = item.title;
    cell.additionalInfoLabel.text = item.address;
    //电话按钮
    if (item.phone&&item.phone!=(id)[NSNull null]&&item.phone.length>0) {
        [cell.phoneButton setEnabled:YES];
        [cell.phoneButton setBackgroundImage:[UIImage imageNamed:@"xl_phone.png"] forState:UIControlStateNormal];
        cell.phoneButton.tag = index;
        if (self.delegate && [self.delegate respondsToSelector:@selector(phoneButtonAction:)]) {
            [cell.phoneButton addTarget:self.delegate action:@selector(phoneButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    } else {
        [cell.phoneButton setEnabled:NO];
        [cell.phoneButton setBackgroundImage:nil forState:UIControlStateNormal];
    }
    //地图按钮
    if (item.point&&item.point!=(id)[NSNull null]&&item.point.length>0) {
        [cell.mapButton setEnabled:YES];
        [cell.mapButton setBackgroundImage:[UIImage imageNamed:@"mylocat.png"] forState:UIControlStateNormal];
        cell.mapButton.tag = index;
        if (self.delegate && [self.delegate respondsToSelector:@selector(mapButtonAction:)]) {
            [cell.mapButton addTarget:self.delegate action:@selector(mapButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    } else {
        [cell.mapButton setEnabled:NO];
        [cell.mapButton setBackgroundImage:[UIImage imageNamed:@"bt-地图-灰.png"] forState:UIControlStateNormal];
    }
}

-(void)configInfoWithGuidCell:(WorkQueryCell *)cell withItem:(StreetWorkEntity *)item atIndex:(NSInteger)index
{
    cell.mainInfoLabel.text = item.name;
        cell.guidButton.tag = index;
        if (self.delegate && [self.delegate respondsToSelector:@selector(guidButtonAction:)]) {
            [cell.guidButton addTarget:self.delegate action:@selector(guidButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
}
-(void)configInfoWithEnterpriseGuidCell:(WorkQueryCell *)cell withItem:(CommonWorkGuideEntity *)item atIndex:(NSInteger)index
{
//    cell.mainInfoLabel.text = item.title;
    cell.mainInfoLabel.text = item.respectiveIssue;
    cell.guidButton.tag = index;
    if (self.delegate && [self.delegate respondsToSelector:@selector(guidCommonButtonAction:)]) {
        [cell.guidButton addTarget:self.delegate action:@selector(guidEnterpriseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}
-(void)configInfoWithCommonGuidCell:(WorkQueryCell *)cell withItem:(StreetWorkGuideEntity *)item atIndex:(NSInteger)index
{
//    cell.mainInfoLabel.text = item.title;
     cell.mainInfoLabel.text = item.name;
    cell.guidButton.tag = index;
    if (self.delegate && [self.delegate respondsToSelector:@selector(guidCommonButtonAction:)]) {
        [cell.guidButton addTarget:self.delegate action:@selector(guidCommonButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
}

-(NSDictionary *)getTargetConfigForCellAtIndex:(NSIndexPath *)indexPath
{
    //super implements return the item in dataList
//    return nil;
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[self.dataList objectAtIndex:indexPath.row],@"dataItem", nil];
    return dic;
}

-(ConfigableViewController *)getCellTargetViewControllerForName:(NSString *)className
{
    //产生下一级页面
    Class tempClass =  NSClassFromString(className);
    if (!tempClass) {
        
        return nil;
    }
    ConfigableViewController *vc = [[tempClass alloc]initWithNibName:className bundle:nil];
    return vc;
}

-(NSString *)getButtomTips
{
    return @"";
}

//-(NSString *)httpGet:(NSString*)requesturl operationWithPath:(NSString *)path
//{
//    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:requesturl customHeaderFields:nil];
//    MKNetworkOperation *op = [engine operationWithPath:path params:nil httpMethod:@"GET" ssl:NO];
//    [op addCompletionHandler:^(MKNetworkOperation *operation) {
//        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
//    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
//        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
//    }];
//    [engine enqueueOperation:op];
//}
//-(NSString*)httpPost:(NSString *)posturl parameters:(NSDictionary *)dict
//{
//    MKNetworkEngine *engine = [[MKNetworkEngine alloc] initWithHostName:posturl customHeaderFields:nil];
////    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
////    [dic setValue:@"admin" forKey:@"username"];
////    [dic setValue:@"admin" forKey:@"password"];
//    MKNetworkOperation *op = [engine operationWithPath:@"" params:dict httpMethod:@"POST"];
//    [op addCompletionHandler:^(MKNetworkOperation *operation) {
//        NSLog(@"[operation responseData]-->>%@", [operation responseString]);
//    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
//        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
//    }];
//    [engine enqueueOperation:op];
//}
@end
